<template>
  <MainLayout>
    <div class="task-detail-page">
      <!-- 页面标题 -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">任务详情</h2>
        <n-button 
          text 
          type="primary" 
          @click="$router.back()"
        >
          <template #icon>
            <n-icon size="18">
              <ArrowBackOutline />
            </n-icon>
          </template>
          返回
        </n-button>
      </div>
      
      <!-- 任务详情卡片 -->
      <div v-if="isLoading" class="flex justify-center items-center py-12">
        <n-spin size="large" />
      </div>
      
      <div v-else-if="!currentTask" class="text-center py-12">
        <n-empty description="任务不存在或已被删除">
          <template #icon>
            <n-icon size="48">
              <AlertCircleOutline />
            </n-icon>
          </template>
          <n-button type="primary" @click="$router.back()">
            返回任务列表
          </n-button>
        </n-empty>
      </div>
      
      <div v-else>
        <n-card 
          class="mb-6 shadow-sm"
          :bordered="false"
        >
          <template #header>
            <div class="flex justify-between items-start">
              <div>
                <h3 class="text-xl font-semibold flex items-center">
                  {{ currentTask.title }}
                  <n-tag 
                    v-if="currentTask.is_important" 
                    type="error" 
                    size="small" 
                    class="ml-2"
                  >
                    重要
                  </n-tag>
                  <n-tag 
                    v-if="currentTask.is_my_day" 
                    type="primary" 
                    size="small" 
                    class="ml-2"
                  >
                    我的一天
                  </n-tag>
                </h3>
                <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  {{ currentTask.group_name || '未分组' }}
                  <span v-if="currentTask.due_date" class="ml-2">
                    截止日期: {{ currentTask.due_date }}
                  </span>
                </div>
              </div>
              <n-select 
                v-model:value="currentTask.status" 
                :options="statusOptions"
                class="w-32"
                @update:value="updateTaskStatus"
              />
            </div>
          </template>
          
          <div class="mt-4">
            <h4 class="text-lg font-semibold mb-2">任务描述</h4>
            <p class="text-gray-700 dark:text-gray-300">
              {{ currentTask.description || '无描述' }}
            </p>
          </div>
          
          <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-3">
              <div class="text-sm text-gray-500 dark:text-gray-400">创建时间</div>
              <div class="font-medium">{{ formatDate(currentTask.created_at) }}</div>
            </div>
            <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-3">
              <div class="text-sm text-gray-500 dark:text-gray-400">更新时间</div>
              <div class="font-medium">{{ formatDate(currentTask.updated_at || currentTask.created_at) }}</div>
            </div>
            <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-3">
              <div class="text-sm text-gray-500 dark:text-gray-400">任务状态</div>
              <div class="font-medium">{{ getStatusText(currentTask.status) }}</div>
            </div>
          </div>
          
          <!-- 任务操作按钮 -->
          <div class="mt-6 flex flex-wrap gap-3">
            <n-button 
              type="primary" 
              @click="showEditTaskDialog = true"
            >
              <template #icon>
                <n-icon size="18">
                  <CreateOutline />
                </n-icon>
              </template>
              编辑任务
            </n-button>
            
            <n-button 
              type="error" 
              @click="showDeleteConfirm = true"
            >
              <template #icon>
                <n-icon size="18">
                  <TrashOutline />
                </n-icon>
              </template>
              删除任务
            </n-button>
            
            <n-button 
              text 
              @click="toggleMyDay"
            >
              <template #icon>
                <n-icon size="18">
                  <CalendarOutline />
                </n-icon>
              </template>
              {{ currentTask.is_my_day ? '取消我的一天' : '标记为我的一天' }}
            </n-button>
            
            <n-button 
              text 
              @click="toggleImportant"
            >
              <template #icon>
                <n-icon size="18">
                  <StarOutline />
                </n-icon>
              </template>
              {{ currentTask.is_important ? '取消重要' : '标记为重要' }}
            </n-button>
          </div>
        </n-card>
        
        <!-- 任务日志 -->
        <n-card 
          class="mb-6 shadow-sm"
          :bordered="false"
        >
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-semibold">任务日志</h3>
              <n-button 
                type="primary" 
                @click="showAddLogDialog = true"
              >
                <template #icon>
                  <n-icon size="18">
                    <AddOutline />
                  </n-icon>
                </template>
                添加日志
              </n-button>
            </div>
          </template>
          
          <div v-if="taskLogs.length === 0" class="text-center py-8">
            <n-empty description="暂无任务日志">
              <template #icon>
                <n-icon size="32">
                  <DocumentTextOutline />
                </n-icon>
              </template>
              <n-button type="primary" @click="showAddLogDialog = true">
                添加第一条日志
              </n-button>
            </n-empty>
          </div>
          
          <div v-else>
            <n-timeline>
              <n-timeline-item 
                v-for="log in taskLogs" 
                :key="log.log_id"
                :timestamp="formatDate(log.created_at)"
              >
                {{ log.content }}
              </n-timeline-item>
            </n-timeline>
          </div>
        </n-card>
        
        <!-- 编辑任务对话框 -->
        <n-dialog v-model:show="showEditTaskDialog" title="编辑任务" width="600px">
          <n-form 
            :model="editTaskForm" 
            :rules="editTaskRules"
            ref="editTaskFormRef"
          >
            <n-form-item path="title">
              <n-input 
                v-model:value="editTaskForm.title" 
                placeholder="请输入任务标题"
              />
            </n-form-item>
            
            <n-form-item path="group_id">
              <n-select 
                v-model:value="editTaskForm.group_id" 
                placeholder="请选择任务分组"
                :options="groupOptions"
              >
                <template #prefix>
                  <n-icon size="18">
                    <ListOutline />
                  </n-icon>
                </template>
              </n-select>
            </n-form-item>
            
            <n-form-item path="description">
              <n-input
                v-model:value="editTaskForm.description"
                type="textarea"
                placeholder="请输入任务描述"
                :autosize="{ minRows: 3, maxRows: 6 }"
              />
            </n-form-item>
            
            <div class="grid grid-cols-2 gap-4">
              <n-form-item>
                <n-date-picker 
                  v-model:value="editTaskForm.due_date" 
                  type="date"
                  placeholder="选择截止日期"
                />
              </n-form-item>
              
              <div class="flex items-center space-x-4">
                <n-checkbox v-model:checked="editTaskForm.is_important">重要任务</n-checkbox>
                <n-checkbox v-model:checked="editTaskForm.is_my_day">我的一天</n-checkbox>
              </div>
            </div>
          </n-form>
          <template #footer>
            <div class="flex justify-end space-x-2">
              <n-button @click="showEditTaskDialog = false">取消</n-button>
              <n-button 
                type="primary" 
                @click="updateTask"
                :loading="isUpdating"
              >
                保存修改
              </n-button>
            </div>
          </template>
        </n-dialog>
        
        <!-- 添加日志对话框 -->
        <n-dialog v-model:show="showAddLogDialog" title="添加任务日志" width="500px">
          <n-form 
            :model="logForm" 
            :rules="logRules"
            ref="logFormRef"
          >
            <n-form-item path="content">
              <n-input
                v-model:value="logForm.content"
                type="textarea"
                placeholder="请输入日志内容"
                :autosize="{ minRows: 4, maxRows: 8 }"
                autofocus
              />
            </n-form-item>
          </n-form>
          <template #footer>
            <div class="flex justify-end space-x-2">
              <n-button @click="showAddLogDialog = false">取消</n-button>
              <n-button 
                type="primary" 
                @click="addTaskLog"
                :loading="isAddingLog"
              >
                添加日志
              </n-button>
            </div>
          </template>
        </n-dialog>
        
        <!-- 删除确认对话框 -->
        <n-dialog 
          v-model:show="showDeleteConfirm" 
          title="确认删除" 
          type="warning"
        >
          <div class="text-center py-4">
            <n-icon size="48" type="error" class="mb-4" />
            <p class="mb-4">您确定要删除这个任务吗？</p>
            <p class="text-gray-500 dark:text-gray-400">此操作不可恢复，任务的所有日志也将被删除。</p>
          </div>
          <template #footer>
            <div class="flex justify-end space-x-2">
              <n-button @click="showDeleteConfirm = false">取消</n-button>
              <n-button 
                type="error" 
                @click="deleteTask"
                :loading="isDeleting"
              >
                确认删除
              </n-button>
            </div>
          </template>
        </n-dialog>
      </div>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'
import { useGroupStore } from '@/store/group'
import { useTaskStore } from '@/store/task'
import { UpdateTaskRequest, CreateTaskLogRequest } from '@/types'
import { 
  ArrowBackOutline, 
  CreateOutline, 
  TrashOutline, 
  CalendarOutline, 
  StarOutline, 
  AddOutline, 
  DocumentTextOutline,
  ListOutline, 
  AlertCircleOutline
} from '@vicons/ionicons5'
import type { FormInstance } from 'naive-ui'

// 路由和路由参数
const route = useRoute()
const router = useRouter()
const taskId = computed(() => parseInt(route.params.id as string) || 0)

// 状态
const showEditTaskDialog = ref<boolean>(false)
const showAddLogDialog = ref<boolean>(false)
const showDeleteConfirm = ref<boolean>(false)
const isUpdating = ref<boolean>(false)
const isAddingLog = ref<boolean>(false)
const isDeleting = ref<boolean>(false)
const editTaskFormRef = ref<FormInstance | null>(null)
const logFormRef = ref<FormInstance | null>(null)

// 任务状态选项
const statusOptions = [
  { label: '新任务', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 }
]

// 获取分组store和任务store
const groupStore = useGroupStore()
const taskStore = useTaskStore()

// 从store获取数据
const currentTask = computed(() => taskStore.currentTask)
const taskLogs = computed(() => taskStore.taskLogs)
const isLoading = computed(() => taskStore.isLoading || groupStore.isLoading)
const groups = computed(() => groupStore.groups)

// 分组选项（用于编辑任务时选择分组）
const groupOptions = computed(() => {
  return groups.value.map(group => ({
    label: group.name,
    value: group.group_id
  }))
})

// 编辑任务表单
const editTaskForm = reactive<UpdateTaskRequest>({
  group_id: 0,
  title: '',
  description: '',
  is_important: false,
  is_my_day: false,
  status: 0,
  due_date: undefined
})

// 编辑任务表单规则
const editTaskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 1, max: 100, message: '任务标题长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 日志表单
const logForm = reactive<CreateTaskLogRequest>({
  content: ''
})

// 日志表单规则
const logRules = {
  content: [
    { required: true, message: '请输入日志内容', trigger: 'blur' },
    { min: 1, max: 500, message: '日志内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date)
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap = {
    0: '新任务',
    1: '进行中',
    2: '已完成'
  }
  return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 更新任务状态
const updateTaskStatus = async () => {
  if (!currentTask.value) return
  await taskStore.updateTask(currentTask.value.task_id, { status: currentTask.value.status })
}

// 更新任务
const updateTask = async () => {
  if (!editTaskFormRef.value || !currentTask.value) return
  
  try {
    await editTaskFormRef.value.validate()
    isUpdating.value = true
    await taskStore.updateTask(currentTask.value.task_id, editTaskForm)
    showEditTaskDialog.value = false
    // 刷新任务详情
    await taskStore.fetchTaskDetail(taskId.value)
  } catch (error) {
    console.error('更新任务失败:', error)
  } finally {
    isUpdating.value = false
  }
}

// 删除任务
const deleteTask = async () => {
  if (!currentTask.value) return
  
  try {
    isDeleting.value = true
    await taskStore.deleteTask(currentTask.value.task_id)
    showDeleteConfirm.value = false
    // 跳转到任务列表
    router.push('/')
  } catch (error) {
    console.error('删除任务失败:', error)
  } finally {
    isDeleting.value = false
  }
}

// 添加任务日志
const addTaskLog = async () => {
  if (!logFormRef.value || !currentTask.value) return
  
  try {
    await logFormRef.value.validate()
    isAddingLog.value = true
    await taskStore.createTaskLog(currentTask.value.task_id, logForm)
    showAddLogDialog.value = false
    // 刷新任务日志
    await taskStore.fetchTaskLogs(currentTask.value.task_id)
    // 重置日志表单
    logForm.content = ''
  } catch (error) {
    console.error('添加日志失败:', error)
  } finally {
    isAddingLog.value = false
  }
}

// 切换我的一天标记
const toggleMyDay = async () => {
  if (!currentTask.value) return
  await taskStore.updateTask(currentTask.value.task_id, { 
    is_my_day: !currentTask.value.is_my_day 
  })
}

// 切换重要标记
const toggleImportant = async () => {
  if (!currentTask.value) return
  await taskStore.updateTask(currentTask.value.task_id, { 
    is_important: !currentTask.value.is_important 
  })
}

// 监听当前任务变化，更新编辑表单
watch(currentTask, (newTask) => {
  if (newTask) {
    editTaskForm.group_id = newTask.group_id
    editTaskForm.title = newTask.title
    editTaskForm.description = newTask.description || ''
    editTaskForm.is_important = newTask.is_important
    editTaskForm.is_my_day = newTask.is_my_day
    editTaskForm.status = newTask.status
    editTaskForm.due_date = newTask.due_date
  }
})

// 页面加载时获取数据
onMounted(async () => {
  // 获取分组列表
  await groupStore.fetchGroups()
  // 获取任务详情
  if (taskId.value) {
    await taskStore.fetchTaskDetail(taskId.value)
    // 获取任务日志
    await taskStore.fetchTaskLogs(taskId.value)
  }
})
</script>

<style scoped>
.task-detail-page {
  max-width: 1200px;
  margin: 0 auto;
}
</style>
